package top.revery.admin.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Configuration;
import top.revery.api.advice.BaseException;

import java.io.IOException;

/**
 * <h1> --- 服务端错误信息拦截 --- </h1>
 * Created by  revery.top jun
 * Date  2019-12-13 12:06
 */
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            // 这里直接拿到我们抛出的异常信息
            String message = Util.toString(response.body().asReader());
            try {
                JSONObject jsonObject = JSON.parseObject(message);
                return new BaseException(jsonObject.getString("message"),jsonObject.getInteger("status"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException ignored) {
        }
        return decode(methodKey, response);
    }
}
